package com.lw.mall.web.lw;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lw.mall.entity.Classification;
import com.lw.mall.entity.OrderItem;
import com.lw.mall.entity.Product;
import com.lw.mall.entity.User;
import com.lw.mall.entity.pojo.ResultBean;
import com.lw.mall.filter.AuthorizationFilter;
import com.lw.mall.service.ClassificationService;
import com.lw.mall.service.ProductService;
import com.lw.mall.service.exception.LoginException;
import com.lw.mall.service2.OrderItemService2;
import com.lw.mall.service2.OrderService2;
import com.lw.mall.service2.ProductService2;
import com.lw.mall.utils.FileUtil;
import com.lw.mall.vo.MallIndexVo;
import com.lw.mall.vo.SellDetailListVo;
import com.lw.mall.vo.SellListVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 * 用户卖出的商品
 * 订单管理和商品管理
 */
@Slf4j
@Controller
public class SellProductOrderController {

    @Autowired
    private OrderService2 orderService2;

    @Autowired
    private OrderItemService2 orderItemService2;

    @Autowired
    private ProductService2 productService2;

    @Autowired
    private ClassificationService classificationService;

    @Autowired
    private ProductService productService;

    @RequestMapping("/lw/maiList.html")
    public String userSell(){
        return "/mall/mai/list";
    }


    //用户上架的商品修改
    @RequestMapping("lw/productEdit.html")
    public String userproductlist(){
        return "/mall/mai/productlist";
    }

    //用户上架商品修改
    @RequestMapping("/lw/product/toEdit.html")
    public String toEdit(int id, Map<String, Object> map) {
        Product product = productService.findById(id);
        Classification classification = classificationService.findById(product.getCsid());
        product.setCategorySec(classification);
        map.put("product", product);
        return "/mall/mai/productEdit";
    }


    @ResponseBody
    @RequestMapping("/lw/product/list.do")
    public ResultBean<List<MallIndexVo>> listProduct(int pageindex,
                                                     @RequestParam(value = "pageSize",
                                                         defaultValue = "15") int pageSize, HttpServletRequest request) {
        final User user = (User) request.getSession().getAttribute("user");
        final List<Product> list = productService2.list(new LambdaQueryWrapper<Product>().eq(Product::getSellId, user.getId()));
        final List<MallIndexVo> collect = list.stream().map(item -> {
            final MallIndexVo mallIndexVo = new MallIndexVo();
            BeanUtils.copyProperties(item, mallIndexVo);
            return mallIndexVo;
        }).collect(Collectors.toList());
        return new ResultBean<>(collect);
    }

    @ResponseBody
    @RequestMapping("/lw/product/getTotal")
    public ResultBean<Integer> getTotal(HttpServletRequest request) {
        final User user = (User) request.getSession().getAttribute("user");
        if(user==null)
             throw new LoginException("请登录");
        final List<Product> list = productService2.list(new LambdaQueryWrapper<Product>().eq(Product::getSellId, user.getId()));
        final int total = list.size();
        return new ResultBean<>(total);
    }

    //用户下架商品
    @RequestMapping("/lw/product/del.do")
    @ResponseBody
    public ResultBean<Boolean> del(int id) {
        productService.delById(id);
        return new ResultBean<>(true);
    }

    //上架商品更新
    @RequestMapping(method = RequestMethod.POST, value = "lw/product/update.do")
    public void update(int id,
                       String title,
                       Double marketPrice,
                       Double shopPrice,
                       String desc,
                       int csid,
                       MultipartFile image,
                       HttpServletRequest request,
                       HttpServletResponse response) throws Exception {
        Product product = productService.findById(id);
        product.setTitle(title);
        product.setMarketPrice(new BigDecimal(marketPrice));
        product.setShopPrice(new BigDecimal(shopPrice));
        product.setDesc(desc);
//        product.setIsHot(isHot);
        product.setCsid(csid);
        product.setPdate(new Date());
        if (!image.isEmpty()) {
            String imgUrl = FileUtil.saveFileAliyun(image);
            if (StringUtils.isNotBlank(imgUrl)) {
                product.setImage(imgUrl);
            }
        }
        boolean flag = false;
        try {
            productService.update(product);
            flag = true;
        } catch (Exception e) {
            throw new Exception(e);
        }
        if (!flag) {
            request.setAttribute("message", "更新失败！");
        }
        response.sendRedirect("/mall/lw/productEdit.html");
    }

    /**
     *
     * 以下是订单的相关信息
     *
     */
    /**
     * "/mall/lw/getTotal.do"
     * 获取该卖家订单的总数
     *
     * //localhost:8081/mall/lw/getTotal.do
     * @return
     */
    @ResponseBody
    @RequestMapping("/lw/getTotal.do")
    public ResultBean<Integer> getTotal() {

        final List<Integer> list = this.getOrderIdByUser();
        final int total = list.size();
        return new ResultBean<>(total);
    }

    /**
     *
     * /mall/admin/order/list.do?pageindex=0
     * 获取该卖家所有订单
     * @param pageindex
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/lw/list.do")
    public ResultBean<List<SellListVo>> listData(int pageindex,
                                                 @RequestParam(value = "pageSize",
                                                    defaultValue = "15") int pageSize,
                                                 HttpServletRequest request) {
//        Pageable pageable = new PageRequest(pageindex, pageSize, null);
//        List<Order> list = orderService.findAll(pageable).getContent();
        // 获取到 order的id
        final List<Integer> OrderIdList = this.getOrderIdByUser();
        //获取该用户卖出商品的order项
//        final List<Order> list = orderService2.listByIds(OrderIdList);
        final List<SellListVo> list = orderService2.getOrderSellListByIds(OrderIdList);
        return new ResultBean<>(list);
    }

    /**
     * 获取用户卖出订单项
     * @param orderId
     * @return
     */
    @ResponseBody
//    @GetMapping ("lw/getDetail.do")
    public ResultBean<List<OrderItem>> getDetail(int orderId) {

        final List<OrderItem> list =
                orderItemService2.list(new LambdaQueryWrapper<OrderItem>().
                        eq(OrderItem::getOrderId, orderId));
        final List<OrderItem> collect = list.stream().map(item -> {
            final Integer productId = item.getProductId();
            final Product product = productService2.getById(productId);
            item.setProduct(product);
            return item;
        }).collect(Collectors.toList());

        return new ResultBean<>(collect);
    }

    @ResponseBody
    @GetMapping ("lw/getDetail.do")
    public ResultBean<List<SellDetailListVo>> getDetail2(int orderId) {

        final List<OrderItem> list =
                orderItemService2.list(new LambdaQueryWrapper<OrderItem>().
                        eq(OrderItem::getOrderId, orderId));
        List<SellDetailListVo> collect=orderItemService2.geSellDetailList(orderId);

        return new ResultBean<>(collect);
    }

    /**
     * 提供user 获取order号不是 orderItem
     * @return
     */
    private List<Integer> getOrderIdByUser(){
        //获取登录用户
        final User user = AuthorizationFilter.userLogin.get();
        //where sell_id=user.id
        final List<OrderItem> list =
                orderItemService2.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getSellId, user.getId()));
        final List<Integer> collect = list.stream().map(OrderItem::getOrderId).distinct().collect(Collectors.toList());
        return collect;

    }
}
